package com.never.website.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.never.website.dao.AccountDao;
import com.never.website.model.Account;
import com.never.website.util.DataHelper;

@Service
@Configurable
public class LoginAuthenDetailService implements UserDetailsService{
	
	@Autowired
	private AccountDao accountDao;
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
		Account accountAdmin = null;
		try {
			accountAdmin = accountDao.getUserByName(username, DataHelper.UserRole.ROLE_FOR_ADMIN.getCode());
		} catch (Exception e) {
			e.printStackTrace();
		}
		accountAdmin = accountDao.getUserByName(username, DataHelper.UserRole.ROLE_FOR_ADMIN.getCode());
		/*accountAdmin = new Account();
		accountAdmin.setActive(true);
		accountAdmin.setUsername("test");
		accountAdmin.setId(100);
		accountAdmin.setRole(DataHelper.UserRole.ROLE_FOR_ADMIN.getCode());
		accountAdmin.setEmail("ddd");*/
		if (accountAdmin != null) {
			AUTHORITIES.add(new SimpleGrantedAuthority(DataHelper.UserRole.ROLE_FOR_ADMIN.getCode()));
			return new User(username, accountAdmin.getPassword(), AUTHORITIES);
		} else {
			throw new UsernameNotFoundException("User is authozization!!");
		}
	}
}
